package com.vcourse.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.vcourse.service.edu.entity.Subject;
import com.vcourse.service.edu.entity.excel.ExcelSubjectData;
import com.vcourse.service.edu.listener.ExcelSubjectDataListener;
import com.vcourse.service.edu.mapper.SubjectMapper;
import com.vcourse.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vcourse.service.edu.vo.SubjectVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Zengsh123
 * @since 2020-05-25
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Resource
    private SubjectMapper subjectMapper;

    @Override
    public void batchImport(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelSubjectData.class, new ExcelSubjectDataListener(subjectMapper))
                .excelType(ExcelTypeEnum.XLSX)
                .sheet().doRead();
    }

    @Override
    public List<SubjectVo> nestedList() {
        List<Subject> subjectList = this.list();
        List<SubjectVo> nestedList = new ArrayList<>();
        for (Subject subject : subjectList) {
            if (subject.getParentId().equals("0")) {
                SubjectVo subjectVo = new SubjectVo();
                subjectVo.setId(subject.getId()).setTitle(subject.getTitle())
                        .setSort(subject.getSort());
                nestedList.add(subjectVo);
                listToTree(subjectList, subjectVo, subjectVo.getId());
            }
        }
        return nestedList;
    }

    /**
     * 搜寻一个目录下的所有子目录
     * @param subjectList 目录集合
     * @param parent 当前目录
     * @param parentId 当前目录ID，即其子目录的parentId
     */
    private void listToTree(List<Subject> subjectList, SubjectVo parent, String parentId) {
        for (Subject subject : subjectList) {
            if (subject.getParentId().equals(parentId)) {
                SubjectVo subjectVo = new SubjectVo();
                subjectVo.setId(subject.getId()).setTitle(subject.getTitle())
                        .setSort(subject.getSort());
                parent.getChildren().add(subjectVo);
                listToTree(subjectList, subjectVo, subjectVo.getId());
            }
        }
    }
}
